/**
 * FtpClientUtilities.java
 * @author: liuex
 * 2007-12-25 ����01:21:39
 *
 * note: 
 */
package org.lex.ftp.ui.explorer;

import java.io.IOException;
import java.nio.charset.Charset;
import javax.swing.ActionMap;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

import org.lex.ftp.FTP;
import org.lex.ftp.model.ApacheFTPModel;
import org.lex.ftp.model.FTPModel;
import org.lex.ftp.model.NullFTPModel;
import org.lex.ftp.net.FTPUtils;
import org.lex.ftp.net.LogListener;
import org.lex.ftp.net.MyFTPClientFactory;
import org.lex.ftp.util.Actions;
import org.lex.ftp.util.Sound;
import org.lex.net.ftp.FTPURL;
import org.lex.net.ftp.IFTPClient;
import org.lex.net.ftp.IFTPFile;
import org.lex.net.ftp.util.FTPClientFactory;
import org.lex.net.ftp.util.FTPConnector;


public class FTPExplorerUtils {
	public static final IFTPFile[] EMPTY = new IFTPFile[0];

	public static void open(final FTPExplorer explorer, final FTPURL url) {
		final FTPConnector connector = new FTPConnector(explorer.app.getGlobalLogger(), MyFTPClientFactory.getInstance());
		connector.addChangeListener(new ChangeListener() {
			public void stateChanged(ChangeEvent e) {
				if (true == connector.isConnected()) {
					Sound.connect();
					setConnected(explorer.app, true);
					open(explorer, url, connector.getFtpClient());
				} else {
					Sound.error();
				}
			}
		});
		connector.connect(url);
	}

	private static void open(FTPExplorer explorer, FTPURL url, IFTPClient ftp) {
		ftp.setPassiveMode(true);
		FTPModel ftpModel = new ApacheFTPModel();
		ftpModel.setFTPClient(ftp);
		ftpModel.setFTPURL(url);
		explorer.setFTPModel(ftpModel);
		ftpModel.reload();
	}

	public static void openSimple(final FTPExplorer explorer, final FTPURL url) {
		IFTPClient ftp = FTPClientFactory.getDefaultFactory().newFTPClient();
		ftp.setServerCharset(Charset.defaultCharset());
		ftp.addProtocolListener(new LogListener(explorer.app.getGlobalLogger()));
		try {
			ftp.openServer(url.getHost(), url.getPort());
			ftp.login(url.getAuthentication().getUserName(), url.getAuthentication().getPassword());
			Sound.connect();
			open(explorer, url, ftp);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void close(final FTPExplorer explorer) {
		FTPUtils.close(explorer.getFTPClient());
		explorer.setFTPModel(NullFTPModel.getInstance());
		setConnected(explorer.app, false);
	}

	public static void setConnected(FTP app, boolean connected) {
		app.getFTPExplorer().getDirectoryExplorer().setRootVisible(connected);
		ActionMap am = app.getActionMap();
		am.get(Actions.CONNECT).setEnabled(!connected);
		am.get(Actions.DISCONNECT).setEnabled(connected);
	}
}
